package fr.n7.khome.dao;

import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;

import fr.n7.khome.model.Lodging;


/**
 * Implementation of a LodgingDAO using a map.
 * @author clej37
 */
public class LodgingDAOMap implements LodgingDAO {
	
	private Map<Long, Lodging> idToLodgingMap;
	private Long maxID;
	private Queue<Long> freeIds;
	
	public LodgingDAOMap(){
		idToLodgingMap = new HashMap<Long, Lodging>();
		freeIds = new LinkedList<Long>();
		maxID = 0L;
	}
	
	public Long create(Lodging l) {
		Long id;
		if(freeIds.isEmpty()){
			id = maxID++;
		}else{
			id = freeIds.poll();
		}
		idToLodgingMap.put(id, l);
		l.setId(id);
		return id;
	}

	private void reduceFreeIds(){
		while(freeIds.contains(maxID - 1)){
			maxID --;
			freeIds.remove(maxID);
		}
	}
	
	public void delete(Lodging l) {
		Long id = l.getId();
		idToLodgingMap.remove(id);
		freeIds.add(id);
		reduceFreeIds();
	}

	public Collection<Lodging> listAll() {
		return idToLodgingMap.values();
	}

	public Lodging read(Long id) {
		return idToLodgingMap.get(id);
	}

	public void update(Lodging l) {
		Long id = l.getId();
		idToLodgingMap.put(id, l);
	}
}